package com.knife.common.utils;

import com.knife.common.constants.BaseConstants;
import com.knife.common.exception.CommonException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author tianhao.luo@hand-china.com
 */
public class KnifeSpringValidUtil {


    /**
     * 校验是否有错误数据
     * @param bindingResult 错误数据
     * @return 错误提示
     */
    private static String buildErrorMessage(BindingResult bindingResult){
        // 1.参数校验
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        if (!CollectionUtils.isEmpty(fieldErrors)) {
            return checkParam(fieldErrors);
        }
        return null;
    }

    /**
     * 抛出{@link CommonException}异常
     * @param bindingResult 错误数据
     */
    public static void throwCommonException(BindingResult bindingResult){
        String errorMessage = buildErrorMessage(bindingResult);
        if (StringUtils.isNotEmpty(errorMessage)){
            throw new CommonException(errorMessage);
        }
    }

    /**
     * 检查参数
     * @param fieldErrors 异常的属性
     * @return 错误信息
     */
    private static String checkParam(List<FieldError> fieldErrors) {
        return fieldErrors.stream().map(FieldError::getDefaultMessage).collect(Collectors.joining(","));
    }

}
